import { hapTasks } from '@ohos/hvigor-ohos-plugin';
import * as fs from 'fs';
import * as child_process from 'child_process';

export function signPlugin(str?: string) {
    return{
        pluginId: 'signPlugin',
        apply(pluginContext) {
            pluginContext.registerTask({
                //编写自定义任务
                name: 'signPlugin',
                run: (taskContext) => {
                    let outPath = taskContext.modulePath + '/build/default/outputs/default';
                    let signPath = taskContext.modulePath + '/sign-tool';
                    if (fs.existsSync(outPath + '/entry-default-unsigned.hap')) {
                        fs.copyFile(outPath + '/entry-default-unsigned.hap', signPath + '/entry-default-unsigned.hap', (res) => {
                        });
                        child_process.execFileSync(signPath + '/sign_debug.bat', null, {
                            cwd: signPath
                        })
                        fs.copyFile(signPath + '/entry-debug-signed.hap', outPath + '/entry-default-signed.hap', (res) => {
                        });
                    }
                },
                dependencies: ['default@SignHap'],
                postDependencies: ['assembleHap']
            })
        }
    }
}

export default {
    system: hapTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
    plugins:[signPlugin()]         /* Custom plugin to extend the functionality of Hvigor. */
}
